import { createStore } from 'vuex'
import axios from 'axios'
import { useRouter } from 'vue-router'
const router = useRouter()
// 安全读写 localStorage
const safeLocalStorage = {
  get(key) {
    try {
      return localStorage.getItem(key)
    } catch (e) {
      console.error('LocalStorage access error:', e)
      return null
    }
  },
  set(key, value) {
    try {
      localStorage.setItem(key, value)
    } catch (e) {
      console.error('LocalStorage access error:', e)
    }
  },
  remove(key) {
    try {
      localStorage.removeItem(key)
    } catch (e) {
      console.error('LocalStorage access error:', e)
    }
  }
}

export default createStore({
  actions: {
    async login({ commit }, credentials) {
      try {
        const { data } = await axios.post('/api/users/login/', credentials)
        if (!data.user_id) throw new Error('Invalid response structure')
        safeLocalStorage.set('userId', data.user_id)
        safeLocalStorage.set('username', data.username)
        return { success: true }
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '登录失败，请检查网络连接'
        }
      }
    },

    async logout({ commit }) {

      safeLocalStorage.remove('userId')
      safeLocalStorage.remove('username')
    },

    // 优化后的注册逻辑
    async register({ commit }, userData) {
      try {
        const { data } = await axios.post('/api/users/register/', userData)
        if (data.user_id) {
          return { success: true }
        }
        return { success: false, message: data.message || '注册失败' }
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message ||
            `注册失败：${error.message}`
        }
      }
    }
  }
})